package com.exam.role.action;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;

import com.exam.base.action.BaseAction;
import com.exam.role.model.Module;
import com.exam.role.service.RoleService;

public class ModuleAction extends BaseAction {
	private RoleService roleService;
	private Module module = new Module();
	private List<Module> modules;

	public List<Module> getModules() {
		return modules;
	}

	public void setModules(List<Module> modules) {
		this.modules = modules;
	}

	/**
	 * 查询
	 * 
	 * @return
	 */
	public String search() {
		setModules(roleService.findMenusByPage(module, getPage()));
		return SUCCESS;
	}

	/**
	 * 新增跳转
	 * 
	 * @return
	 */
	public String newMenu() {
		setModules(roleService.findSubMenus());
		return INPUT;
	}

	/**
	 * 编辑跳转
	 * 
	 * @return
	 */
	public String editMenu() {
		Module menu = roleService.getMenuById(new Integer(getRequest()
				.getParameter("mid")));
		menu.setParentId(menu.getParent().getId());
		setModule(menu);
		setModules(roleService.findSubMenus());
		return INPUT;
	}

	/**
	 * 保存
	 * 
	 * @return
	 */
	public String saveMenu() {
		Module parent = roleService.getMenuById(module.getParentId());
		module.setParent(parent);
		/**
		 * id为空、新增，否则修改
		 */
		if (module.getId() != null) {
			Module moduleDb = roleService.getMenuById(module.getId());
			try {
				BeanUtils.copyProperties(moduleDb, module);
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
			roleService.save(moduleDb);
		} else {
			roleService.save(module);
		}
		// setModules(roleService.findSubMenus());
		return search();
	}

	public RoleService getRoleService() {
		return roleService;
	}

	public void setRoleService(RoleService roleService) {
		this.roleService = roleService;
	}

	public Module getModule() {
		return module;
	}

	public void setModule(Module module) {
		this.module = module;
	}
}
